//
//  EditController.m
//  LeaveLight
//
//  Created by 张 on 2019/3/5.
//  Copyright © 2019年 xsl. All rights reserved.
//

#import "EditController.h"
#import "AddImageView.h"
@interface EditController ()
@property (nonatomic, strong) AddImageView *menView;

@property (nonatomic, strong) TempateCareOne * careView1;
@property (nonatomic, strong) TempateCareTwo * careView2;
@property (nonatomic, strong) TempateCareThere *careView3;

@property (assign,nonatomic) NSInteger oldColorIndex;
@property (assign,nonatomic) NSInteger oldFontIndex;
@property (assign,nonatomic) BOOL isSave;

/**
 当前展示的view
 */
@property (nonatomic, strong) UIView * showView;

@end

@implementation EditController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.naviView.backgroundColor = [UIColor clearColor];
    [self.view addSubview:self.menView];
    if (self.isEdit) {
        [self setRightButtonWithTitle:@"" image:[UIImage imageNamed:@"完成"] himage:[UIImage imageNamed:@"完成"] action:@selector(saveEdit) subtitle:@"" subimage:[UIImage imageNamed:@"保存到草稿箱"] subhimage:[UIImage imageNamed:@"保存到草稿箱"] subaction:@selector(saveToFraft)];
        [self.deepChooseView setHidden:YES];
        [self.deepEditView setHidden:NO];
        [self.menView setHidden:NO];
        self.model.is_edit = YES;
        [PAGEGUIDEMANAGER showGuideImgArr:@[@"字体引导页",@"背景色引导页",@"图片引导页",@"首页详情 编辑页面 -模版引导页",@"水印引导页",@"草稿箱引导页",@"图片可放大缩小",@"保存引导页"]];
    }else{
        [self.deepEditView setHidden:YES];
        [self.deepChooseView setHidden:NO];
        [self.menView setHidden:YES];
        self.model.is_edit = NO;
    }
    [self configDeepView];
//    [self configModelView];
    [self.view bringSubviewToFront:self.menView];
    
    weakify(self);
    [QMUITips showLoadingInView:self.view];
    [self getChickenDetailWithid:StringIsEmpty(self.model.chicken_model.chicken_id) ? self.model.chicken_model.ID : self.model.chicken_model.chicken_id Success:^(ZDBaseModel * _Nonnull model) {
        strongify(self);
        [QMUITips hideAllTips];
        [self configModelView];
        self.collectBtn.selected = model.is_collect == 1 ? NO : YES;
    } failed:^(NSString * _Nonnull error) {
        [QMUITips hideAllTips];
        [QMUITips showWithText:error];
    }];
}

- (void)backBtnPressed:(UIButton *)sender{
    if (self.isEdit && !self.isSave) {
        weakify(self);
        QMUIAlertAction *action1 = [QMUIAlertAction actionWithTitle:@"保存到草稿箱" style:QMUIAlertActionStyleDefault handler:^(__kindof QMUIAlertController *aAlertController, QMUIAlertAction *action) {
            strongify(self);
            [self saveToFraft];
        }];
        action1.buttonAttributes =  @{NSFontAttributeName: [UIFont fontWithName:@"PingFangSC-Regular" size: 14],NSForegroundColorAttributeName: [UIColor colorWithRed:255/255.0 green:175/255.0 blue:4/255.0 alpha:1.0]};
        QMUIAlertAction *action2 = [QMUIAlertAction actionWithTitle:@"不保存" style:QMUIAlertActionStyleDefault handler:^(__kindof QMUIAlertController *aAlertController, QMUIAlertAction *action) {
            strongify(self);
            [self selfPopViewController];
        }];
        action2.buttonAttributes = @{NSFontAttributeName: [UIFont fontWithName:@"PingFangSC-Regular" size: 14],NSForegroundColorAttributeName: [UIColor colorWithRed:32/255.0 green:32/255.0 blue:32/255.0 alpha:1.0]};
        QMUIAlertAction *action3 = [QMUIAlertAction actionWithTitle:@"取消" style:QMUIAlertActionStyleCancel handler:NULL];
        action3.buttonAttributes = @{NSFontAttributeName: [UIFont fontWithName:@"PingFangSC-Regular" size: 14],NSForegroundColorAttributeName: [UIColor colorWithRed:32/255.0 green:32/255.0 blue:32/255.0 alpha:1.0]};
        QMUIAlertController *alertController = [QMUIAlertController alertControllerWithTitle:@"尚未编辑完成确定离开此页面吗？" message:@"" preferredStyle:QMUIAlertControllerStyleAlert];
        NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
        paragraphStyle.alignment = NSTextAlignmentCenter;
        alertController.alertTitleAttributes = @{NSFontAttributeName: [UIFont fontWithName:@"PingFangSC-Regular" size: 16],NSForegroundColorAttributeName: [UIColor colorWithRed:32/255.0 green:32/255.0 blue:32/255.0 alpha:1.0],NSParagraphStyleAttributeName:paragraphStyle};
        [alertController addAction:action1];
        [alertController addAction:action2];
        [alertController addAction:action3];
        [alertController showWithAnimated:YES];
    }
    else{
        [self selfPopViewController];
    }
}

- (void)selfPopViewController{
    NSInteger viewCounts = self.navigationController.viewControllers.count;
    if (viewCounts > 2) {
        UIViewController *tmp = [self.navigationController.viewControllers objectAtIndex:viewCounts - 2];
        if ([tmp isKindOfClass:[EditController class]]) {
            [self.navigationController popToViewController:[self.navigationController.viewControllers objectAtIndex:viewCounts - 3] animated:YES];
        }
        else{
            [self.navigationController popViewControllerAnimated:YES];
        }
    }
    else{
        [self.navigationController popViewControllerAnimated:YES];
    }
}


#pragma mark - private

- (AddImageView *)menView{
    if (!_menView) {
        _menView = [[AddImageView alloc] initWithFrame:CGRectMake(0, SCREEN_HEIGHT - SafeAreaInsetsConstantForDeviceWithNotch.bottom - 49 - 200, SCREEN_WIDTH, 200)];
        _menView.selectedItem = 0;
        _menView.cellStyle = CellStyleFont;
        weakify(self);
        _menView.userSelectedBlock = ^(CellStyle cellStyle, NSInteger row, id  _Nonnull setValue) {
            
            strongify(self);
            if (cellStyle == CellStyleFont) {
                UIFont *font = (UIFont *)setValue;
                [font fontWithSize:14];
                self.model.font = font;
                if (self.careView1) {
                    self.careView1.contentLabel.font = font;
                    self.careView1.authorTextField.font = [font fontWithSize:12];
                    self.careView1.logoTip.font = [font fontWithSize:12];
                }
                else if (self.careView2){
                    self.careView2.describleTextView.font = font;
                    self.careView2.authorTextField.font = [font fontWithSize:12];
                }
                else if (self.careView3) {
                    self.careView3.contentLabel.font = font;
                    self.careView3.authorTextField.font = [font fontWithSize:12];
                    self.careView3.logoTip.font = [font fontWithSize:12];
                }
                self.oldFontIndex = row;
            }
            else if (cellStyle == CellStyleBGColor){
                if (self.careView1) {
                    self.careView1.backgroundColor = setValue;
                }
                else if (self.careView2){
                    self.careView2.backgroundColor = setValue;
                }
                else if (self.careView3){
                    self.careView3.backgroundColor = setValue;
                }
                self.model.bgColor = setValue;
                self.oldColorIndex = row;
            }
            else if (cellStyle == CellStyleTemplate){
                if (self.careView1) {
                    [self.careView1 removeFromSuperview];
                    self.careView1 = nil;
                }
                else if (self.careView2){
                    [self.careView2 removeFromSuperview];;
                    self.careView2 = nil;
                }
                else if (self.careView3){
                    [self.careView3 removeFromSuperview];;
                    self.careView3 = nil;
                }
                self.model.chicken_model.template_type = row == 0 ? 2 : row == 1 ? 1 : row + 1;
                [self configModelView];
                
            }
            else if (cellStyle == CellStyleImage){
                if (self.careView1) {
                    [self.careView1 removeFromSuperview];
                    self.careView1 = nil;
                }
                else if (self.careView2){
                    [self.careView2 removeFromSuperview];;
                    self.careView2 = nil;
                }
                else if (self.careView3){
                    [self.careView3 removeFromSuperview];;
                    self.careView3 = nil;
                }
                if ([setValue isKindOfClass:[NSURL class]]) {
                    NSURL *url = (NSURL *)setValue;
                    self.model.choiseImage = [[SDWebImageManager sharedManager].imageCache imageFromCacheForKey:url.absoluteString];
                }
                else if([setValue isKindOfClass:[QMUIAsset class]]){
                    QMUIAsset *asset = (QMUIAsset *)setValue;
                    self.model.choiseImage = [asset previewImage];
                }
                [self configModelView];
            }
            else if (cellStyle == CellStyleTheSeal){
                self.model.thescaleStyle = row + 1;
                if (self.careView1) {
                    [self.careView1 removeFromSuperview];
                    self.careView1 = nil;
                }
                else if (self.careView2){
                    [self.careView2 removeFromSuperview];;
                    self.careView2 = nil;
                }
                else if (self.careView3){
                    [self.careView3 removeFromSuperview];;
                    self.careView3 = nil;
                }
                [self configModelView];
            }
        };
    }
    return _menView;
}

#pragma mark - config
- (void)configModelView
{
    NSInteger tag = self.model.chicken_model.template_type;
    switch (tag) {
        case 1:
        case 2:
        case 3:
        case 6:{
            self.careView1 = [[TempateCareOne alloc]initWithFrame:CGRectMake(42, NavigationContentTop, SCREEN_WIDTH - 84, SCREEN_HEIGHT - 35 - TabBarHeight - NavigationContentTop)];
            [self.view addSubview:self.careView1];
            [self.careView1 setCardModel:self.model];
            [self.view sendSubviewToBack:self.careView1];
        }break;
        case 4:
        case 5:{
            self.careView2 = [[TempateCareTwo alloc]initWithFrame:CGRectMake(42, NavigationContentTop, SCREEN_WIDTH - 84, SCREEN_HEIGHT - 35 - TabBarHeight - NavigationContentTop)];
            [self.view addSubview:self.careView2];
            [self.careView2 setCardModel:self.model];
            [self.view sendSubviewToBack:self.careView2];
        }break;
        case 7:
        case 8:{
            self.careView3 = [[TempateCareThere alloc]initWithFrame:CGRectMake(42, NavigationContentTop, SCREEN_WIDTH - 84, SCREEN_HEIGHT - 35 - TabBarHeight - NavigationContentTop)];
            [self.view addSubview:self.careView3];
            [self.careView3 setCardModel:self.model];
            [self.view sendSubviewToBack:self.careView3];
        }break;
        
        default:
            break;
    }
}

- (void)configDeepView
{
    for (UIView * view in self.deepChooseView.subviews) {
        if ([view isKindOfClass:[QMUIButton class]]) {
            ((QMUIButton*)view).spacingBetweenImageAndTitle = 5;
            ((QMUIButton*)view).imagePosition = QMUIButtonImagePositionTop;
        }
    }
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

#pragma mark - deepViewAction

- (IBAction)deepChooseClick:(QMUIButton *)sender {
    switch (sender.tag) {
        case 10:{
            if (sender.selected) {
                [self deleteCollectWithid:StringIsEmpty(self.model.chicken_model.chicken_id) ? self.model.chicken_model.ID : self.model.chicken_model.chicken_id Success:^{
                    sender.selected = NO;
                } failed:^(NSString * _Nonnull error) {
                    [QMUITips showWithText:error];
                }];
            }else
            {
                [self addCollectWithid:StringIsEmpty(self.model.chicken_model.chicken_id) ? self.model.chicken_model.ID : self.model.chicken_model.chicken_id imgUrl:self.model.chicken_model.images template_type:self.model.chicken_model.template_type Success:^{
                    sender.selected = YES;
                } failed:^(NSString * _Nonnull error) {
                    [QMUITips showWithText:error];
                }];
            }
            
        }break;
        case 11:{
            EditController * edit = [[EditController alloc]initWithNibName:@"EditController" bundle:nil];
            self.model.chicken_model.is_edit = YES;
            edit.model = self.model;
            edit.isEdit = YES;
            [self.navigationController pushViewController:edit animated:YES];
        }break;
        case 12:{
            [self saveEdit];
        }break;
        case 13:{
            [(self.careView1 ? self.careView1 : self.careView2) ? (self.careView1 ? self.careView1 : self.careView2) : self.careView3 screenShotViewSaveLibrary];
        }break;
        default:
            break;
    }
}

- (IBAction)deepEditClick:(UIButton *)sender {
    if (sender.selected) {
        return;
    }
    for (UIView * view in self.deepEditView.subviews) {
        if ([view isKindOfClass:[UIButton class]]) {
            ((UIButton *)view).selected = NO;
        }
    }
    sender.selected = !sender.selected;
    if (self.menView.frame.size.height < 200) {
        self.menView.frame = CGRectMake(0, SCREEN_HEIGHT - SafeAreaInsetsConstantForDeviceWithNotch.bottom - 49 - 200, SCREEN_WIDTH, 200);
    }
    switch (sender.tag) {
        case 0:{
            self.menView.selectedItem = self.model.bgColor ? self.oldFontIndex : 0;
            self.menView.cellStyle = CellStyleFont;
        }break;
        case 1:{
            self.menView.selectedItem = self.model.font ? self.oldColorIndex : 0;
            self.menView.cellStyle = CellStyleBGColor;
        }break;
        case 2:{
            self.menView.selectedItem = 0;
            self.menView.cellStyle = CellStyleImage;
        }break;
        case 3:{
            self.menView.selectedItem = self.model.chicken_model.template_type == 1 ? 1 : self.model.chicken_model.template_type == 2 ? 0 : self.model.chicken_model.template_type - 1;
            self.menView.cellStyle = CellStyleTemplate;
        }break;
        case 4:{
            self.menView.selectedItem = 0;
            self.menView.cellStyle = CellStyleTheSeal;
        }break;
            
        default:
            break;
    }
}

#pragma mark - action
/**
 保存到草稿箱
 */
- (void)saveToFraft
{
    self.isSave = YES;
    [QMUITips showSucceed:@"保存草稿箱成功"];
    self.model.timestamp = [[NSDate date] timeIntervalSince1970];
    self.model.completeImg = [(self.careView1 ? self.careView1 : self.careView2) ? (self.careView1 ? self.careView1 : self.careView2) : self.careView3 qmui_snapshotImageAfterScreenUpdates:YES];
    [CONTENTMANAGER addTemplateModelWith:self.model];
}

/**
 确认保存 - 分享
 */
- (void)saveEdit
{
    [ShareView initWithShareChooseViewChooseBlock:^(NSInteger selIndex) {
        if (selIndex < 999 && [[UMSocialManager defaultManager] isInstall:selIndex]) {
            UMSocialMessageObject *messageObject = [UMSocialMessageObject messageObject];
            UMShareImageObject * shareObject = [UMShareImageObject shareObjectWithTitle:@"留光" descr:@"一抹时光 一抹情" thumImage:[(self.careView1 ? self.careView1 : self.careView2) ? (self.careView1 ? self.careView1 : self.careView2) : self.careView3 qmui_snapshotImageAfterScreenUpdates:YES]];
            shareObject.shareImage = [(self.careView1 ? self.careView1 : self.careView2) ? (self.careView1 ? self.careView1 : self.careView2) : self.careView3 qmui_snapshotImageAfterScreenUpdates:YES];
            //分享消息对象设置分享内容对象
            messageObject.shareObject = shareObject;
            weakify(self);
            [[UMSocialManager defaultManager] shareToPlatform:selIndex messageObject:messageObject currentViewController:self completion:^(id data, NSError *error) {
                if (error) {
                    [QMUITips showError:@"分享失败"];
                    self.isSave = NO;
                }else{
                    strongify(self);
                    self.isSave = YES;
                    [QMUITips showSucceed:@"分享成功"];
                }
            }];
        }else if(selIndex == 999){
            //保存本地
            self.isSave = YES;
            [(self.careView1 ? self.careView1 : self.careView2) ? (self.careView1 ? self.careView1 : self.careView2) : self.careView3 screenShotViewSaveLibrary];
        }else{
            self.isSave = NO;
            [QMUITips showWithText:@"分享失败"];
        }
    }];
}

@end
